define(["knockout", "durandal/app", "jquery", "i18nCommon", "core", "mask", "panalManager", "string", "ui", "resizable"], 
		function (ko, app, $, i18n, core, mask, PanalManager, stringUtils) {
	var panalUtils, Panal;
	
	Panal = function(content, settings, param){
	    this.settings = $.extend({}, Panal.defaultSettings, settings);
	    this.settings.sourceTitle = this.settings.title;
        this.content = content;
        this.param = param;     //参数用来传递给panal页面使用的参数
	};
	
	Panal.defaultSettings = {
		width: 400,
		height: 300,
		draggable: true,
		resizable: false,
		minBtn: true,
		maxBtn: false,
		closeBtn: true,
		max: false,           //初始化为最大化窗口
		heightMax: false,     //初始化为高度最大化
		titleShow: true,
		title: "",
		panalListTitle: "",   //在桌面的面板列表上显示的标题，用在title为空的情况
		top: null,
		left: null,
		right: null,
		bottom: null,
		margin: 3,
		mouseoutClose: false, //鼠标移出即关闭
		pointShow: false,     //面板是否带有指示角
		pointBorder: "left",  //left/right/top/bottom 在哪个边显示
		pointPosition: 10,    //距离顶点的位置,从左边到右或者从上到下的距离
		modal: false,         //是否模态
		contentOpacity: 1,    //内容透明度默认设置为1
		headOpacity: 1,       //标题透明度默认不透明
		transition: false,    //转场动画
		multi: false,         //是否只可能存在一个页面，如果可能被多次打开，请设置为true
		multiId: null,        //用来标识被多次打开的字符串
		headShow: true,       //隐藏标题栏
		fullScreen: false,    //全屏（遮盖上下工具栏）
		refresh: false,		//单实例再次getInstance时是否需要刷新
		onFocus: function(e){},
		onClick: function(e){},
		onDbClick: function(e){},
//		onBeforeDrag: function(e){},
		onStartDrag: function(e, ui){},
		onDrag: function(e, ui){},
		onStopDrag: function(e, ui){},
		onResize: function(e){},
		onClose: function(){},
		onBeforeClose: function(){return true;}
	};
	
	/** 初始化面板 **/
	Panal.prototype.init = function(){
		Panal.initPanal(this);
		Panal.initHead(this);
		Panal.initButton(this);
		Panal.initContent(this);
		Panal.initPoint(this);
		PanalManager.panalEvent();
		this.active();
		PanalManager.regPanal(this);
	};
	
	/** 激活面板 **/
	Panal.prototype.active = function(){
		var that = this;
		if(!this.settings.modal){
			this.zIndex = PanalManager.getNextZIndex();
		}else{
			if(!this._mask){
				this._mask = mask.getInstance();
			}
			this._mask.show();
			this.zIndex = PanalManager.getNextModalZIndex();
		}
		this.panalElement.css({
			"z-index": that.zIndex
		});
		this._headElement.removeClass("app-panal-inactive");
		//this._backgroundElement.removeClass("app-panal-inactive");
		if(this.settings.pointShow){
			this._point.css({"border-right-color": this._backgroundElement.css("background-color")});
		}
		this.settings.onFocus();
		PanalManager.activeAfter(this);
	};
	
	/** 不激活面板 **/
	Panal.prototype.inActive = function(){
		this._headElement.addClass("app-panal-inactive");
		//this._backgroundElement.addClass("app-panal-inactive");
		//if(this.settings.pointShow){
		//	this._point.css({"border-right-color": this._backgroundElement.css("background-color")});
		//}
	};
	
	/** 最大化面板 **/
	Panal.prototype.max = function(){
		var width = 6, height = 84, top = '51px', bottom = '32px', left = '2px';
		if (this.settings.fullScreen) {
			width = 0;
			height = 0;
			top = '0px';
			bottom = '0px';
			left = '0px';
		}
		this.panalElement.css({
			"left": left, 
			"top": top, 
			"bottom": bottom,
			"width": document.documentElement.clientWidth - width,
			"height": document.documentElement.clientHeight - height});
		this.resize();
		this.settings.onResize();
		this._sizeState = "max";
	};

	/** 高度最大化面板 **/
	Panal.prototype.heightMax = function(){
		this.panalElement.css({
			"top": "51px", 
			"bottom": "32px",
			"height": document.documentElement.clientHeight - 84});
		this.resize();
		this.settings.onResize();
	};
	
	/** 隐藏面板 **/
	Panal.prototype.min = function(){
		this.hide();
	};
	
	Panal.prototype.hide = function(){
		this.panalElement.hide();
	};
	
	/** 移动面板 **/
	Panal.prototype.move = function(x, y){
		if(this.settings.left){
			this.settings.left = this.settings.left + x;
			this.panalElement.css({"left": this.settings.left});
		}else if(this.settings.right){
			this.settings.right = this.settings.right - x;
			this.panalElement.css({"right": this.settings.right});
		}
		if(this.settings.top){
			this.settings.top = this.settings.top + y;
			this.panalElement.css({"top": this.settings.top});
		}else if(this.settings.bottom){
			this.settings.bottom = this.settings.bottom - y;
			this.panalElement.css({"bottom": this.settings.bottom});
		}
	};
	
	/** 移动面板到 **/
	Panal.prototype.moveTo = function(x, y){
		this.settings.left = x;
		this.settings.right = null;
		this.settings.top = y;
		this.settings.bottom = null;
		this.panalElement.css({
			"left": this.settings.left,
			"right": this.settings.right,
			"top": this.settings.top,
			"bottom": this.settings.bottom
		});
	};
	
	/** 更新标题 **/
	Panal.prototype.updateTitle = function(title, titleTip){
		this.settings.title = title;
		this._headElement.find(".app-panal-head-title").text(title);
		if(titleTip){
			this._headElement.find(".app-panal-head-title").attr("title", titleTip);
		}else{
			this._headElement.find(".app-panal-head-title").attr("title", "");
		}
	};
	
	Panal.prototype.getPanalElement = function(){
		return this.panalElement;
	};
	
	Panal.prototype.show = function(){
		this.panalElement.show();
	};

	Panal.prototype.isShow = function () {
		return this.panalElement.is(':visible');
	};
	
	Panal.prototype.close = function(){
		if(this.settings.modal){
			this._mask.remove();
			this._mask = null;
		}
		this.settings.onClose();
		PanalManager.unRegPanal(this);
		this.panalElement.remove();
	};

	/** 与close的区别只有是否调用回调函数 **/
	Panal.prototype.cancelClose = function(){
		if(this.settings.modal){
			this._mask.remove();
			this._mask = null;
		}
		PanalManager.unRegPanal(this);
		this.panalElement.remove();
	};
	
	Panal.prototype.center = function(){
		this.panalElement.css({
			"left": (document.documentElement.clientWidth - this.panalElement.width())/2,
			"top": (document.documentElement.clientHeight - this.panalElement.height())/2
		});
	};
	
	Panal.prototype.normalSize = function(){
		var that = this;
		if(!that.settings.left && !that.settings.right){
			that.settings.left = (document.documentElement.clientWidth - that.settings.width)/2;
		}
		if(!that.settings.top && !that.settings.bottom){
			that.settings.top = (document.documentElement.clientHeight - that.settings.height)/2;
		}
		this.panalElement.css({
			"width": that.settings.width,
			"height": that.settings.height,
			"left": that.settings.left,
			"top": that.settings.top,
			"right": that.settings.right,
			"bottom": that.settings.bottom
		});
		this._contentElement.css({
			'margin-left': that.settings.margin + 'px',
			'margin-right': that.settings.margin + 'px'
		});
		
		this.resize();
		this.settings.onResize();
		this._sizeState = "nomal";
	};
	
	/** 
	*初始化panal大小和位置
    *@param setting {width,height,top,right,right,bottom}
	*/
	Panal.prototype.resize = function(setting){
		if (setting) {
			if(!setting.left && !setting.right){
				setting.left = (document.documentElement.clientWidth - setting.width)/2;
			}
			if(!setting.top && !setting.bottom){
				setting.top = (document.documentElement.clientHeight - setting.height)/2;
			}
			this.panalElement.css({
				"width": setting.width,
				"height": setting.height,
				"left": setting.left,
				"top": setting.top,
				"right": setting.right,
				"bottom": setting.bottom
			});
		}

		this._contentContainerElement.css({
			"height": this.panalElement.height() - this._headElement.height()
		});
		//设置内容
		this._contentElement.css({
			"height": this.panalElement.height() - this._headElement.height(),
			"width": this.panalElement.width() - this.settings.margin*2
		});
	};
	
	/*刷新面板内容*/
	Panal.prototype.update = function(params){
		if (params)
			this.param = params;
		Panal.initContent(this);
	}
	
	/** 初始化面板 **/
	Panal.initPanal = function(p){
		p.panalId = (p.settings.multi ? (p.content + p.settings.multiId) : p.content);
		if (p.settings.headShow)
			p.panalElement = $(Panal.view);
		else
			p.panalElement = $(Panal.viewnohead);
		p.panalElement.attr("panal-id", p.panalId);
		p._headElement = p.panalElement.find(".app-panal-head");
		p._contentContainerElement = p.panalElement.find(".app-panal-content-container");
		p._backgroundElement = p.panalElement.find(".app-panal-background");
		p._contentElement = p.panalElement.find(".app-panal-content");
		//设置panal
		p.panalElement.appendTo($("body"));
		p.normalSize();
		//可以被拖拽。对于非AMD标准的jquery插件不能使用 require("***")
		if(p.settings.draggable){
			/**
			p.panalElement.draggable({
				handle: p._headElement,
				onBeforeDrag: p.settings.onBeforeDrag,
				onStartDrag: p.settings.onStartDrag,
				onDrag: p.settings.onDrag,
				onStopDrag: p.settings.onStopDrag
			});**/
			p.panalElement.draggable({
				containment: [-(p.settings.width), 0, ($(window).width() + p.settings.width), ($(window).height() + p.settings.height)],
				scroll: false,
				iframeFix: true,
				handle: p._headElement,
				start: p.settings.onStartDrag,
				drag: p.settings.onDrag,
				stop: p.settings.onStopDrag
			});
		}else{
			p._headElement.css({"cursor":"auto"});
		}
		//可调整页面大小
		if(p.settings.resizable){
			p.panalElement.resizable({
				onResize: function(e){
					p.resize();
					p.settings.onResize(e);
				}
			});
		}
		p.panalElement.click(function(){
			p.settings.onClick();
		});
		p.panalElement.dblclick(function(){
			p.settings.onDbClick();
		});
		Panal.initPanalMouseout(p);
	};
	
	/** 面板指示角 **/
	Panal.initPoint = function(p){
		if(p.settings.pointShow){
			p._point = $("<div class='app-panal-point'></div>");
			if(p.settings.pointBorder === "right"){
				p._point.css({
					"transform": "rotate(180deg)",
					"right": "-15px",
					"left": null,
					"top": p.settings.pointPosition,
					"border-right-color": p._backgroundElement.css("background-color")
				});
			}else if(p.settings.pointBorder === "top"){
				p._point.css({
					"transform": "rotate(90deg)",
					"top": "-15px",
					"left": p.settings.pointPosition,
					"border-right-color": p._headElement.css("background-color")
				});
			}else if(p.settings.pointBorder === "bottom"){
				p._point.css({
					"transform": "rotate(270deg)",
					"bottom": "-14px",
					"top": null,
					"left": p.settings.pointPosition,
					"border-right-color": p._backgroundElement.css("background-color")
				});
			}else{
				p._point.css({
					"left": "-15px",
					"top": p.settings.pointPosition,
					"border-right-color": p._backgroundElement.css("background-color")
				});
			}
			p.panalElement.append(p._point);
		}
	};
	
	/** 鼠标移出关闭事件 **/
	Panal.initPanalMouseout = function(p){
		if(p.settings.mouseoutClose){
			p.panalElement.mouseout(function(e){
				if(p.settings.left){
					if(e.pageX < p.settings.left){
						p.close();
					}
					if(e.pageX > p.settings.left + p.settings.width){
						p.close();
					}
				}
				if(p.settings.right){
					if(e.pageX < (document.documentElement.clientWidth - p.settings.width - p.settings.right)){
						p.close();
					}
					if(e.pageX > (document.documentElement.clientWidth - p.settings.right)){
						p.close();
					}
				}
				if(p.settings.top){
					if(e.pageY < p.settings.top){
						p.close();
					}
					if(e.pageY > p.settings.top + p.settings.height){
						p.close();
					}
				}
				if(p.settings.bottom){
					if(e.pageY < (document.documentElement.clientHeight - p.settings.height - p.settings.bottom)){
						p.close();
					}
					if(e.pageY > (document.documentElement.clientHeight - p.settings.bottom)){
						p.close();
					}
				}
			});
		}
	};
	
	/** 初始化面板标头 **/
	Panal.initHead = function(p){
		//模态panal不能使用最小化按钮
		if(p.settings.modal){
			p.settings.minBtn = false;
		}
		p._headElement.find(".app-panal-head-title").text(p.settings.title);
		//设置标题
		if(p.settings.titleShow){
			p._headElement.css({"opacity": p.settings.headOpacity});
		}else{
			p._headElement.css({
				"opacity": p.settings.contentOpacity
			});
			p._headElement.removeClass("app-panal-head-spe").addClass("app-panal-background-spe");
		}
		p._headElement.dblclick(function(){
			if(p.settings.maxBtn){
//				if(p._sizeState === "nomal"){
					p.max();
//				}else if(p._sizeState === "max"){
//					p.normalSize();
//				}
			}
			p.active();
		}).click(function(){
			p.active();
		});
	};
	
	/** 初始化面板内容 **/
	Panal.initContent = function(p){
		//设置背景透明
		p._backgroundElement.css({
			"opacity": p.settings.contentOpacity
		});
		if (p.uniqueID == undefined)
			p.uniqueID = core.generateId("app-panal");
		p._contentElement.attr("id", p.uniqueID);
		//载入页面内容
		if(p.content){
			if(p.settings.transition){
				app.setRoot(p.content, "entrance", p.uniqueID); 
			}else{
				app.setRoot(p.content, null, p.uniqueID); 
			}
		}
	};
	
	/** 初始化面板按钮 **/
	Panal.initButton = function(p){
		if(p.settings.closeBtn){
			//关闭操作
			p.panalElement.find(".app-panal-head-button-btn-close").click(function(){
				if (p.settings.onBeforeClose())
					p.close();
			}).attr("title", i18n.textCommonPanalCloseBtn);
		}else{
			p.panalElement.find(".app-panal-head-button-btn-close").hide();
		}
		if(!p.settings.minBtn){
			p.panalElement.find(".app-panal-head-button-btn-min").hide();
		}else{
			p.panalElement.find(".app-panal-head-button-btn-min").click(function(){
				p.min();
			}).attr("title", i18n.textCommonPanalMinBtn);
		}
		if(!p.settings.maxBtn){
			p.panalElement.find(".app-panal-head-button-btn-max").hide();
		}else{
			p.panalElement.find(".app-panal-head-button-btn-max").click(function(){
				p.max();
			}).attr("title", i18n.textCommonPanalMaxBtn);
		}
	};
	
	Panal.view = [
		"<div class='app-panal app-panal-font-spe'>",
		"<div class='app-panal-head app-panal-head-spe'>",
			"<span class='app-panal-head-title'></span>",
			"<div class='app-panal-head-button'>",
			    "<svg width='16' height='22' version='1.1' xmlns='http://www.w3.org/2000/svg' class='app-panal-head-button-btn app-panal-head-button-btn-close'>",
					//"<circle cx='8' cy='10' r='7' stroke='#FFFFFF' stroke-width='2' fill='red'/>",
			        "<line x1='5' y1='7' x2='11' y2='13'  style='stroke:white;stroke-width:2'/>",
			        "<line x1='11' y1='7' x2='5' y2='13'  style='stroke:white;stroke-width:2'/>",
			    "</svg>",
			    "<svg width='16' height='22' version='1.1' xmlns='http://www.w3.org/2000/svg' class='app-panal-head-button-btn app-panal-head-button-btn-min app-panal-head-button-distence'>",
			        //"<circle cx='8' cy='10' r='7' stroke='#FFFFFF' stroke-width='2' fill='green'/>",
			        "<line x1='5' y1='10' x2='11' y2='10'  style='stroke:white;stroke-width:2'/>",
			    "</svg>",
				    "<svg width='16' height='22' version='1.1' xmlns='http://www.w3.org/2000/svg' class='app-panal-head-button-btn app-panal-head-button-btn-max app-panal-head-button-distence'>",
			        //"<circle cx='8' cy='10' r='7' stroke='#FFFFFF' stroke-width='2' fill='blue'/>",
			        "<line x1='5' y1='7' x2='11' y2='7'  style='stroke:white;stroke-width:2'/>",
			        "<line x1='11' y1='7' x2='11' y2='13'  style='stroke:white;stroke-width:2'/>",
			        "<line x1='11' y1='13' x2='5' y2='13'  style='stroke:white;stroke-width:2'/>",
			        "<line x1='5' y1='13' x2='5' y2='7'  style='stroke:white;stroke-width:2'/>",
			    "</svg>",
			"</div>",
		"</div>",
		"<div class='app-panal-background app-panal-background-spe'></div>",
		"<div class='app-panal-content-container'><div class='app-panal-content' id=''></div></div>",
		"</div>"     
	].join("");
	
	Panal.viewnohead = [
  		"<div class='app-panal app-panal-font-spe'>",
  		"<div class='app-panal-head app-panal-head-spe' style='display:none;height:0;'></div>",
  		"<div class='app-panal-background app-panal-background-spe' style='top:0;'></div>",
  		"<div class='app-panal-content-container' style='top:0;'><div class='app-panal-content' id=''></div></div>",
  		"</div>"     
  	].join("");

	panalUtils = {
		getInstance: function(content, settings, param){
			
			param = param || {};
	        settings = settings || {};
	        // 支持content中添加参数,（主要目的为了减少参数配置）格式：viewPath?p1=value1&p2=value2, 如果 param中有设置，以param为准
	        // 支持content中添加设置参数，设置参数的命名需要添加前缀 "_$_"，以区别于普通参数,如果settings中有设置，以settings中为准 
	        var pos = content.indexOf("?");
		    if(pos > -1){
			    var paramArray = content.substr(pos + 1).split("&"), params;
			    for(var i=0;i<paramArray.length;i++){
				    params = paramArray[i].split("=");
				    if(params[1]){
				    	if(params[0].indexOf("_$_") === 0){
					    	params[0] = params[0].substr(3);
					    	settings[params[0]] = settings[params[0]] || stringUtils.getValue(params[1]);
					    }else{
					    	param[params[0]] = param[params[0]] || stringUtils.getValue(params[1]); 
					    }
				    }
			    }
			    content = content.substring(0, pos);
		    }
			
			var panalId = content;
			if(settings && settings.multi){
				panalId = panalId + settings.multiId;
			}
			if(PanalManager.exist(panalId)){
				var p = PanalManager.getPanal(panalId);
				if (settings.refresh){
					//更新标题
					if (settings.title && settings.title != p.settings.sourceTitle){
						p.settings.sourceTitle  = settings.title;
						p.updateTitle(settings.title);
					}
					p.update(param);
				}
				p.show();
				p.active();
				return p;
			}else{
				var p = new Panal(content, settings, param);
				p.init();
				if (p.settings.max)
					p.max();
				if (p.settings.heightMax)
					p.heightMax();
				return p;
			}
		},
		getPanal: function(panalId){
			return PanalManager.getPanal(panalId);
		},
		getAllPanal: function(){
			return PanalManager.getAllPanal();
		},
		/** 通过面板内部的dom元素获取面板对象 **/
		getPanalByElement: function(element){
			if(!(element instanceof $)){ 
				element = $(element);
			} 
			return this.getPanal(element.parents("div.app-panal:first").attr("panal-id"));
		}
	};
	
	return panalUtils;
	
});